import docx
import re
import os
from utils.file_util import get_files, check_path
from utils.common_util import isEmpty
from excel.service.data import excel_data
from shutil import copyfile

"""
快速读取word中表格数据，返回excel数据对象
    * path：存放word的文件夹目录
    * title：需要读取的内容项(即excel的标题)
"""


def read_word(path, title):
    e = excel_data()  # 创建excel数据对象
    e.title = [re.sub(r"\s", "", item) for item in title]  # 去除任何空白字符
    check_path(path, isdir=True)
    word_list = get_files(path, search="*.docx")
    for word_path in word_list:
        doc = docx.Document(word_path)
        if len(doc.tables) == 0:
            print(f"ERROR:【{word_path}】中不存在表格，请查看文件")
            continue
        table = doc.tables[0]
        table_dict = {key: None for key in e.title}  # 数组存储
        for row in range(len(table.rows)):  # 遍历所有的行列
            table_row = table.rows[row]
            for index, cell in enumerate(table_row.cells):
                if isEmpty(cell.text):  # 如果为空就跳过
                    continue
                cell_text = re.sub(r"\s", "", str(cell.text))  # 去除任何空白字符
                if cell_text in table_dict:
                    table_dict[cell_text] = table_row.cells[index + 1].text  # 读取当前title后的结果
        table_list = [table_dict[key] for key in e.title]  # dict转换为list
        e.main.append(table_list)  # 添加数据
        print(f"In Progress:  读取 {word_path} ")
    return e


"""
快速读取excel中表格数据，返回excel数据对象
    * path：存放word的文件夹目录
    * title：需要读取的内容项(即excel的标题)
"""


def read_excel(path, title):
    e = excel_data()  # 创建excel数据对象
    e.title = [re.sub(r"\s", "", item) for item in title]  # 去除任何空白字符
    check_path(path, isdir=True)
    excel_list = get_files(path, search="*.xlsx")
    for excel_path in excel_list:
        excel = excel_data().load(excel_path).read() # 读取excel
        table_dict = {key: None for key in e.title}  # 数组存储
        for row in excel.main:  # 遍历所有的行列
            for index, cell in enumerate(row):
                if isEmpty(cell):  # 如果为空就跳过
                    continue
                cell_text = re.sub(r"\s", "", str(cell))  # 去除任何空白字符
                if cell_text in table_dict:
                    table_dict[cell_text] = row[index + 1]  # 读取当前title后的结果
        table_list = [table_dict[key] for key in e.title]  # dict转换为list
        e.main.append(table_list)  # 添加数据
        print(f"In Progress:  读取 {excel_path} ")
    return e


"""
快速从excel数据对象中写出到word表格
    * excel_path：要读取的excel文件地址
    * template：写出的word模板
    * dir：写出的文件夹
    * file_name：文件名
"""


def write_word(excel_path, template, dir="word文档汇总", file_name="{姓名}.docx"):
    e = excel_data().load(excel_path).read()
    if not os.path.exists(dir):
        os.mkdir(dir)
    temp_doc = docx.Document(template)  # 打开拷贝的word文件用于读取文件属性
    props = _read_cell_property(temp_doc.tables[0].rows[0].cells[0])  # 读取第一个单元格属性
    file_name_item = _file_name_replace(file_name, e.title)
    for item in e.main:  # 遍历列表数据
        copy_file_name = file_name  # 拷贝原文件名
        for key, value in file_name_item.items():  # 替换文件名为索引
            if item[value]  is None:
                item[value] = ""
            copy_file_name = copy_file_name.replace(key, item[value])
        word_name = os.path.join(dir, copy_file_name)
        copyfile(template, word_name)  # 拷贝模板
        doc = docx.Document(word_name)  # 打开拷贝的word文件
        table = doc.tables[0]
        for row in range(len(table.rows)):  # 遍历word的表格
            table_row = table.rows[row]
            for index, cell in enumerate(table_row.cells):
                cell_text = re.sub(r"\s", "", cell.text)  # 去除任何空白字符
                if not isEmpty(cell_text) and cell_text in e.title:  # 如果word表格列在
                    next_cell = table_row.cells[index + 1]  # 获取下一个单元各
                    cell_text = item[e.title.index(cell_text)]
                    if cell_text is None:
                        cell_text = ""
                    next_cell.text = str(cell_text)  # 写入文本
                    _write_cell_property(next_cell, props)  # 写入属性
        doc.save(word_name)
        print(f"In Progress:  写入 {word_name} ")
    print(f"SUCCESS:  全部写入完成 ")


"""
    替换文件名,私有方法
        返回需要替换的文件名索引字典
"""


def _file_name_replace(file_name, title):
    items = re.findall(r"\{.*?\}", file_name)
    item_dict = {item: title.index(re.sub(r"\{|\}", "", item)) for item in items}
    return item_dict


"""
    读取单元格的属性 ,私有方法
        包括对齐方式、字体格式、字体大小、是否加粗、字体颜色
"""


def _read_cell_property(cell):
    para = cell.paragraphs[0]  # 获取第一段
    run = para.runs[0]  # 获取第一段第一句
    return {
        "alignment": para.alignment,
        "font_name": run.font.name,
        "font_size": run.font.size,
        "font_bold": run.font.bold,
        "font_color": run.font.color.rgb
    }


"""
    写入单元格的属性 ,私有方法
        包括对齐方式、字体格式、字体大小、是否加粗、字体颜色
"""


def _write_cell_property(cell, props):
    para = cell.paragraphs[0]
    run = para.runs[0]
    para.alignment = props["alignment"]
    run.font.name = props["font_name"]
    run.font.size = props["font_size"]
    run.font.bold = props["font_bold"]
    run.font.color.rgb = props["font_color"]
